from flask.views import MethodView,request
from flask import render_template,redirect,url_for,Response
from sqlalchemy import and_
from os import path
import json
from exts import db
from view.plan import geocode,walking
from models import User
class LoginView(MethodView):
    def get(self):
        return render_template("login.html")
    def post(self):
        username = request.form.get("username")
        password = request.form.get("password")
        if not all([username, password]):
            return render_template('login.html', error='数据不全')
        user = User.query.filter(and_(User.username == username,User.password==password)).first()
        if not user:
            return render_template('login.html', error='用户名或密码错误')
        res = redirect(url_for("index"))
        res.set_cookie("username", username)
        return res

class RegisterView(MethodView):
    def get(self):
        return render_template("register.html")
    def post(self):
        username=request.form.get("username")
        password=request.form.get("password")
        if not all([username, password]):
            return render_template('register.html', error='数据不全')
        res=User.query.filter(User.username==username).first()
        if res:
            return render_template('register.html', error='用户名已注册')
        try:
            user=User(username=username,password=password)
            db.session.add(user)
            db.session.commit()
            # print(user)
        except Exception as e:
            return render_template('register.html', error=str(e))
        return redirect(url_for("login"))
class IndexView(MethodView):
    def get(self):
        username=request.cookies.get('username')
        print(username)
        if not username:
            return redirect(url_for("login"))
        return render_template("main.html")
    def post(self):
        start=request.form.get("start")
        final=request.form.get("final")
        username = request.cookies.get('username')
        if not all([start, final]):
            return render_template('main.html', error='数据不全')
        wu_key = "1ec9df4a24601ac918e0b7ab0440f593"
        res = walking(wu_key, geocode(wu_key,start), geocode(wu_key,final))
        paths=res['route']['paths'][0]['steps']
        print(paths)
        print(len(paths))
        return render_template("list.html",paths=paths)
class LogOutView(MethodView):
    def get(self):
        res=redirect(url_for("login"))
        res.delete_cookie("username")
        return res
